package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.StoreInRecordIn;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.pr.entity.UnitOperator;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.*;
import com.wh.wisdomsite.xbox.st.service.IStoreInRecordService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Map;


/**
 * 入库记录Controller
 *
 * @version V1.0
 * @Package: package com.wh.wisdomsite.xbox.server.controller.st
 * @author: 蔡道行
 * @date: 2018-08-08 10:17
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/storeInRecord")
public class StoreInRecordController {

    private static final Log logger = LogFactory.getLog(StoreInRecordController.class);

    @Autowired
    private IStoreInRecordService iStoreInRecordService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 页面跳转
     *
     * @return
     */
    @RequiresPermissions("rules:st_storeInRecord_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index() {
        return "/st/storeInRecord/storeInRecordList";
    }


    /**
     * 获取入库记录集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_storeInRecord_find")
    @RequestMapping(value = "/storeInRecordList.do")
    public void storeInRecordList(HttpServletResponse response, StoreInRecordIn in) {
        try {
            logger.info("加载入库记录数据列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<StoreInRecord> page = new Page<StoreInRecord>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<StoreInRecord> ewStoreInRecord = new EntityWrapper<StoreInRecord>();
            ewStoreInRecord.setEntity(new StoreInRecord());
            //根据项目名称查询
            if (StringUtils.isNotEmpty(in.getPrName())) {
                ewStoreInRecord.like("p.prName", in.getPrName());
            }
            //根据合同编号查询
            if (StringUtils.isNotEmpty(in.getCoNumber())) {
                ewStoreInRecord.like("co.coNumber", in.getCoNumber());
            }
            //根据合同名称查询
            if (StringUtils.isNotEmpty(in.getCoName())) {
                ewStoreInRecord.like("co.coName", in.getCoName());
            }
            //根据入库方式查询
            if (StringUtils.isNotEmpty(in.getStoreWay())) {
                ewStoreInRecord.eq("sir.storeWay", in.getStoreWay());
            }
            //根据入库时间查询
            if (StringUtils.isNotEmpty(in.getStartDate()) && StringUtils.isNotEmpty(in.getEndDate())) {
                ewStoreInRecord.between("sir.pushDate", in.getStartDate(), in.getEndDate() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getStartDate())) {
                ewStoreInRecord.between("sir.pushDate", in.getStartDate(), in.getStartDate() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getEndDate())) {
                ewStoreInRecord.between("sir.pushDate", in.getEndDate(), in.getEndDate() + " " + "23:59:59");
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewStoreInRecord = UserUtils.setEntityWrapper(ewStoreInRecord, "c1", "o1", "p");
            }
            ewStoreInRecord.groupBy("sir.sameRecord");
            ewStoreInRecord.orderBy("createDate", false);
            Page<Map<String, Object>> storeInRecordPage = iStoreInRecordService.getRecordPage(page, ewStoreInRecord);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (storeInRecordPage.getRecords().size() > 0) {
                for (Map<String, Object> storeInRecord : storeInRecordPage.getRecords()) {
                    JSONObject object = new JSONObject(storeInRecord);
                    object.put("stirId", storeInRecord.get("stirId"));
                    object.put("pushDate",simpleDateFormat.format(storeInRecord.get("pushDate")));
                    if(null!=storeInRecord.get("project")){
                        object.put("prName",((Project) storeInRecord.get("project")).getPrName());
                        object.put("prLeader",((Project) storeInRecord.get("project")).getPrLeader());
                    }
                    if(null!=storeInRecord.get("contract")){
                        object.put("coName",((Contract) storeInRecord.get("contract")).getCoName());
                        object.put("coNumber",((Contract) storeInRecord.get("contract")).getCoNumber());
                    }
                    if(null!=storeInRecord.get("unitOperator")){
                        object.put("uoMgr",((UnitOperator) storeInRecord.get("unitOperator")).getUoMgr());
                    }
                    array.put(object);
                }
            }
            json.put("total", storeInRecordPage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载入库记录数据列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载入库记录数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 页面跳转至入库记录详情列表
     *
     * @return
     */
    @RequiresPermissions("rules:st_storeInRecord_desc")
    @RequestMapping(value = "toRecordDescList.do", method = RequestMethod.GET)
    public String toRecordDescList(HttpServletRequest request,String sameRecord) {
        request.setAttribute("sameRecord",sameRecord);
        return "/st/storeInRecord/storeInRecordDescList";
    }


    /**
     * 获取入库记录详情集合
     *
     * @param response
     * @param in
     */
    @RequestMapping(value = "/storeInRecordDescList.do")
    public void storeInRecordDescList(HttpServletResponse response, StoreInRecordIn in) {
        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        try {
            logger.info("获取入库记录详情集合-->>开始");
            Integer total = 0;
            //统一入库标识
            if(StringUtils.isNotEmpty(in.getSameRecord())){
                //设置分页
                if (in.getPage() == 0) in.setPage(1);
                if (in.getRows() == 0) in.setRows(10);
                Page<StoreInRecord> page = new Page<StoreInRecord>();
                page.setCurrent(in.getPage());
                page.setSize(in.getRows());
                //设置条件
                EntityWrapper<StoreInRecord> ewStoreInRecord = new EntityWrapper<StoreInRecord>();
                ewStoreInRecord.setEntity(new StoreInRecord());
                ewStoreInRecord.eq("sir.sameRecord",in.getSameRecord());
                //根据材料名称查询
                if (StringUtils.isNotEmpty(in.getMaterialName())) {
                    ewStoreInRecord.like("ma.materialName", in.getMaterialName());
                }
                //根据材料规格查询
                if (StringUtils.isNotEmpty(in.getStandardType())) {
                    ewStoreInRecord.like("ma.standardType", in.getStandardType());
                }
                ewStoreInRecord.orderBy("sir.createDate", false);
                Page<Map<String, Object>> storeInRecordPage = iStoreInRecordService.getMapsPage(page, ewStoreInRecord);
                if (storeInRecordPage.getRecords().size() > 0) {
                    for (Map<String, Object> storeInRecord : storeInRecordPage.getRecords()) {
                        JSONObject object = new JSONObject(storeInRecord);
                        object.put("pushDate",simpleDateFormat.format(storeInRecord.get("pushDate")));
                        if(null!=storeInRecord.get("supplier")){
                            object.put("supId",((Supplier) storeInRecord.get("supplier")).getSupId());
                            object.put("supName",((Supplier) storeInRecord.get("supplier")).getSupName());
                        }
                        if(null!=storeInRecord.get("material")){
                            object.put("materialName",((Material)storeInRecord.get("material")).getMaterialName());
                            object.put("standardType",((Material)storeInRecord.get("material")).getStandardType());
                            object.put("meteringUnit",((Material)storeInRecord.get("material")).getMeteringUnit());
                        }
                        array.put(object);
                    }
                }
                total = storeInRecordPage.getTotal();
            }
            json.put("total", total);
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("获取入库记录详情集合-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("获取入库记录详情集合-->>Exception" + e.getMessage());
        }
    }

    /**
     * 入库记录详情
     *
     * @param storeInRecordIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:st_storeInRecord_view")
    @RequestMapping("/storeInRecordDesc.do")
    public String storeInRecordDesc(StoreInRecordIn storeInRecordIn, HttpServletRequest request) {
        try {
            logger.info("入库记录详情-->>开始");
            Map<String, Object> storeInRecord = iStoreInRecordService.getMapById(storeInRecordIn.getStirId());
            if (storeInRecord.get("createBy") != null) {
                storeInRecord.put("createBy", UserMapManager.getUserLoginNameInMap(storeInRecord.get("createBy").toString()));
            }
            if (storeInRecord.get("purchaseDetail") != null) {
                storeInRecord.put("reqPerson", UserMapManager.getUserLoginNameInMap(((PurchaseDetail)storeInRecord.get("purchaseDetail")).getReqPerson()));
            }
            if (storeInRecord.get("updateBy") != null) {
                storeInRecord.put("updateBy", UserMapManager.getUserLoginNameInMap(storeInRecord.get("updateBy").toString()));
            }
            request.setAttribute("storeInRecord", storeInRecord);
            logger.info("入库记录详情-->>结束");
        } catch (Exception e) {
            logger.debug("入库记录详情-->>Exception" + e.getMessage());
            e.printStackTrace();
        }
        return "/st/storeInRecord/storeInRecordDesc";
    }
}
